package com.caiheng.api.service.product.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.dao.estate.EstateMapper;
import com.caiheng.api.dao.mer.MerCouponMapper;
import com.caiheng.api.dao.mer.MerMapper;
import com.caiheng.api.dao.platform.PlatformSplitMapper;
import com.caiheng.api.dao.platform.SplitAccountMapper;
import com.caiheng.api.dao.platform.SplitAccountRecordMapper;
import com.caiheng.api.dao.wxuser.*;
import com.caiheng.api.entity.dto.ProductCartDto;
import com.caiheng.api.entity.dto.WalletDto;
import com.caiheng.api.entity.estate.Estate;
import com.caiheng.api.entity.mer.*;
import com.caiheng.api.entity.platform.*;
import com.caiheng.api.entity.product.*;
import com.caiheng.api.entity.wxuser.*;
import com.caiheng.api.exception.TransactionalException;
import com.caiheng.api.pay.wxpay.WxAppPay;
import com.caiheng.api.service.base.impl.BaseServiceImpl;
import com.caiheng.api.service.mer.MerUserService;
import com.caiheng.api.service.platfom.*;
import com.caiheng.api.service.product.*;
import com.caiheng.api.service.sys.SysConfigService;
import com.caiheng.api.service.wxuser.UserMerCouponService;
import com.vdurmont.emoji.EmojiParser;
import com.caiheng.api.dao.product.*;
import com.caiheng.api.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service
public class ProductOrderServiceImpl extends BaseServiceImpl<ProductOrderMapper, ProductOrder>
        implements ProductOrderService {

    @Resource
    private ProductOrderMapper productOrderMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductAttrValueMapper productAttrValueMapper;
    @Resource
    private ProductOrderInfoMapper productOrderInfoMapper;
    @Resource
    private ProductCartMapper productCartMapper;
    @Resource
    private ProductCartService cartService;
    @Resource
    private PlatformSplitMapper platformSplitMapper;
    @Resource
    private ProductService productService;
    @Resource
    private SplitAccountMapper splitAccountMapper;
    @Resource
    private EstateMapper estateMapper;
    @Resource
    private ProductOrderRelationMapper orderRelationMapper;
    @Resource
    private MerMapper merMapper;
    @Resource
    private MerUserService merUserService;
    @Resource
    private MerCouponMapper merCouponMapper;
    @Resource
    private UserMerCouponMapper userMerCouponMapper;
    @Resource
    private UserMerCouponService userMerCouponService;
    @Resource
    private UserCouponsMapper userCouponsMapper;
    @Resource
    private ParameterService parameterService;
    @Resource
    private PlatformPayService platformPayService;
    @Resource
    private SplitAccountService splitAccountService;
    @Resource
    private ProductOrderInfoService productOrderInfoService;

    @Value("${web.imgPrefix}")
    private String imgPrefix;//图片地址

    /**
     * 使用注解控制事务方法的优点:
     * 1.开发团队达成一致约定，明确标注事务方法的编程风格
     * 2.保证事务方法的执行时间尽可能短，不要穿插其他网络操作RPC/HTTP请求或者剥离到事务方法外部
     * 3.不是所有的方法都需要事务，如只有一条修改操作、只读操作不要事务控制
     */
    @Override
    @Transactional
    public String addNormalOrder(User user, UserAddress userAddress, Double allPrice, Integer order_type, String remark, String platform) throws TransactionalException {
        try{
            long order_id = 0;
            String payNo = OrderUtil.getPayNo();
            List<ProductCartDto> cartDtos = cartService.selectAllMerByUserId(user.getId(),1);
            if(CollUtil.isNotEmpty(cartDtos)){
                for (ProductCartDto cartDto : cartDtos){
                    List<ProductCart> carts = cartDto.getCarts();
                    double orderAllPrice = 0d;
                    if(carts != null && carts.size() > 0) {
                        for(ProductCart car : carts) {
                            orderAllPrice += car.getSinglePrice().doubleValue() * car.getCartNum();
                        }
                    }

                    PlatformPay platformPay = platformPayService.getDefaultAccount();
                    Parameter parameter = parameterService.getParameterById(1);
                    //添加 订单表数据
                    ProductOrder order = new ProductOrder();
                    String orderNo = OrderUtil.getOrderNoByTimespan(platformPay.getSysCode());
                    order.setMerId(cartDto.getMerId());

                    if(platform.equals("wxmini")){
                        order.setPlatform(0);
                    }else{
                        order.setPlatform(1);
                    }
                    order.setPayNo(payNo);
                    order.setOrderNo(orderNo);
                    order.setOutTradeNo(orderNo);

                    order.setDiscountRate(0d);

                    //订单类型  0 - 平台商品类  1 - 设备上的商品类  2 - 线下商家活动  3 - 商家优惠券 4 - 团购类
                    order.setOrderType(order_type);
                    order.setUserId(user.getId());
                    order.setTotalPrice(new BigDecimal(orderAllPrice));
                    order.setCouponId(0);
                    order.setNickName(EmojiParser.parseToUnicode(user.getNickName()));

                    order.setPayType(parameter.getProductPayPlatform());

                    order.setPayPlatformId(0);
                    if(platformPay!=null) {
                        if(parameter.getProductPayPlatform() == 1){
                            order.setPayPlatformId(platformPay.getId());
                        }
                    }

                    order.setCouponPrice(new BigDecimal(0));
                    order.setCouponDikouPrice(new BigDecimal(0));
                    order.setUserCouponId(0);
                    order.setUserCouponPrice(new BigDecimal(0));
                    order.setUserCouponDikouPrice(new BigDecimal(0));

                    order.setCreateTime(new Date());
                    order.setPayPrice(new BigDecimal(orderAllPrice));
                    order.setFee(new BigDecimal(orderAllPrice * 0.06 / 100));
                    //订单状态 0 - 未支付  1 - 支付中  2 - 已支付 3 - 待发货  4 - 待收货  5 - 待评价
                    // 6 - 已评价  7 - 订单取消  8 - 退货中 9 - 已退款
                    order.setStatus(0);
                    order.setRemark(remark);

                    order.setEstateId(user.getEstateId());
                    Estate estate = estateMapper.selectById(user.getEstateId());
                    if(estate!=null){
                        order.setPropertyId(estate.getPropertyId());
                    }
                    order.setRealName(user.getNickName());

//                    order.setRealName(userAddress.getReceiverName());
                    order.setUserPhone(user.getPhoneNum());
                    if(userAddress!=null){
                        order.setUserAddress(userAddress.getRoomNo());
                    }
                    order.setIsMerCheck(0);//是否核销
                    order.setVerifyCode(OrderUtil.getVerfiyNo());//核销码
                    order.setSettlementState(0);

                    Mer mer = merMapper.selectById(cartDto.getMerId());
                    if(mer!=null){
                    }
                    int ret = productOrderMapper.insert(order);

                    if(ret <= 0){
                        throw new TransactionalException("productOrderMapper insert error");
                    }else{
                        order_id = order.getId();
                        ProductOrderRelation orderRelation = new ProductOrderRelation();
                        orderRelation.setOrderId(order_id);
                        orderRelation.setPayNo(payNo);
                        orderRelation.setAllPrice(new BigDecimal(allPrice));
                        ret = orderRelationMapper.insert(orderRelation);
                        if(ret <= 0){
                            throw new TransactionalException("orderRelationMapper insert error");
                        }

                        double d1Total = 0, d2Total = 0, d3Total = 0, dTotalFee = 0,dTotalSettlement = 0;
                        if(order_id > 0){
                            //添加 商品详情数据
                            if(carts != null && carts.size() > 0){
                                for(ProductCart cart : carts){
                                    for (int i = 0; i < cart.getCartNum();i++){
                                        ProductOrderInfo orderInfo = new ProductOrderInfo();
                                        orderInfo.setIsFc(0);
                                        orderInfo.setMerId(cartDto.getMerId());
                                        orderInfo.setVerifyCode(OrderUtil.getVerfiyNoAndRandom());//核销码
                                        orderInfo.setVerifyCount(0);
                                        orderInfo.setIsVerify(0);
                                        orderInfo.setSettlementState(0);
                                        orderInfo.setIsDel(0);
                                        orderInfo.setOpSysUserId(0L);
                                        orderInfo.setDelSysUserId(0L);
                                        Product product = productMapper.selectById(cart.getProductId());
                                        if(product != null){
                                            if(user.getPropertyId()!=null){
                                                orderInfo.setPropertyId(user.getPropertyId());
                                            }
                                            if(user.getEstateId()!=null){
                                                orderInfo.setEstateId(user.getEstateId());
                                            }

                                            if(product.getIsCoupon() == 0){
                                                orderInfo.setMerRate(mer.getSubRate());
                                            }else{
                                                orderInfo.setMerRate(mer.getSubCouponRate());
                                            }

                                            ProductAttrValue attrValue = productAttrValueMapper.selectById(cart.getProductAttValueId());
                                            if(attrValue !=null) {
                                                orderInfo.setProductId(attrValue.getProductId());
                                                orderInfo.setOrderId(order_id);
                                                orderInfo.setSinglePrice(attrValue.getPrice());
                                                orderInfo.setTotalMoney(attrValue.getPrice());
                                                orderInfo.setState(1);
                                                orderInfo.setCreateTime(new Date());
                                                orderInfo.setSkuId(attrValue.getId());
                                                orderInfo.setSkuName(attrValue.getSku());
                                                //原价
                                                orderInfo.setOriginPrice(attrValue.getOtPrice());
                                            }
                                        }

                                        orderInfo.setCount(1);

                                        int res = productOrderInfoMapper.insert(orderInfo);
                                        if(res <= 0){
                                            throw new TransactionalException("productOrderInfoMapper insert error");
                                        }
                                    }

                                    //删除购物车数据
                                    cart.setIsDel(1);
                                    cart.setCheckState(0);
                                    int res = productCartMapper.updateById(cart);
                                    if(res <= 0){
                                        throw new TransactionalException("productOrderInfoMapper insert error");
                                    }
                                }
                            }
                        }

                        //平台分润
                        order.setPlatformSplit(new BigDecimal(d1Total));
                        //业主分润
                        order.setProprietorSplit(new BigDecimal(d2Total));
                        //物业公司分润
                        order.setPropertySplit(new BigDecimal(d3Total));

                        //商家手续费和结算金额计算
                        if(mer != null){
                            order.setMerSubType(mer.getSubType());
                            order.setMerFee(new BigDecimal(dTotalFee));//商家手续费（分佣）
                            order.setMerSettlement(new BigDecimal(dTotalSettlement));//清算金额
                        }

                        ret = productOrderMapper.updateById(order);
                        if(ret <= 0){
                            throw new TransactionalException("productOrderMapper insert error");
                        }
                    }
                }
            }
            if(order_id > 0){
                return payNo;
            }else{
                return null;
            }
        }catch (RuntimeException ex){
            ex.printStackTrace();
            throw new TransactionalException("productOrderInfoMapper insert error");
        }
    }

    @Transactional
    @Override
    public long buyNow(User user, UserAddress userAddress, int order_type, int count, ProductAttrValue attrValue, String remark,String platform) throws TransactionalException {
        try{
            double allPrice = 0;
            double d1Total = 0, d2Total = 0, d3Total = 0, dTotalFee = 0, dTotalSettlement = 0;
            allPrice = count * attrValue.getPrice().doubleValue();

            Product product = productMapper.selectById(attrValue.getProductId());

            PlatformPay platformPay = platformPayService.getDefaultAccount();
            Parameter parameter = parameterService.getParameterById(1);

            Mer mer = merMapper.selectById(product.getMerId());
            String payNo = OrderUtil.getPayNo();
            //添加 订单表数据
            ProductOrder order = new ProductOrder();
            String orderNo = OrderUtil.getOrderNoByTimespan(platformPay.getSysCode());
            if(platform.equals("wxmini")){
                order.setPlatform(0);
            }else{
                order.setPlatform(1);
            }
            order.setPayNo(payNo);
            order.setOrderNo(orderNo);
            order.setOutTradeNo(orderNo);

            //订单类型  0 - 平台商品类  1 - 设备上的商品类  2 - 线下商家活动  3 - 商家优惠券 4 - 团购类
            order.setOrderType(order_type);
            order.setUserId(user.getId());
            order.setTotalPrice(new BigDecimal(allPrice));
            order.setCreateTime(new Date());
            order.setTotalNum(count);
            order.setNickName(EmojiParser.parseToUnicode(user.getNickName()));
            order.setVoucherId(product.getVoucherId());
            order.setPayType(parameter.getProductPayPlatform());

            order.setPayPlatformId(0);
            if(platformPay!=null) {
                if(mer.getPayPlatformId() > 0){
                    platformPay = platformPayService.getById(mer.getPayPlatformId());
                }
                if(parameter.getProductPayPlatform() == 1){
                    order.setPayPlatformId(platformPay.getId());
                }
            }

            //设置是否是上门服务
            order.setIsAppointment(product.getIsVisit());

            //商家抵扣券
            order.setCouponId(0);
            order.setCouponPrice(new BigDecimal(0));
            order.setCouponDikouPrice(new BigDecimal(0));

            //平台优惠券
            order.setUserCouponId(0);
            order.setUserCouponPrice(new BigDecimal(0));
            order.setUserCouponDikouPrice(new BigDecimal(0));

            order.setPayPrice(new BigDecimal(allPrice));
            order.setFee(new BigDecimal(allPrice * 0.06 / 100));
            order.setStatus(0);//订单状态 0 - 未支付  1 - 支付中  2 - 已支付 3 - 待发货  4 - 待收货  5 - 待评价 6 - 已评价  7 - 订单取消  8 - 退货中 9 - 已退款
            order.setRemark(remark);
            order.setIsMerCheck(0);//是否核销
            order.setSettlementState(0);
            order.setUserPhone(user.getPhoneNum());
            order.setVerifyCode(OrderUtil.getVerfiyNo());//核销码
            order.setVoucherDikouPrice(new BigDecimal(0));
            if(product!=null){
                order.setMerId(product.getMerId());
            }
            order.setEstateId(user.getEstateId());
            order.setPropertyId(user.getPropertyId());
            order.setRealName(user.getNickName());

            if(mer != null){
                if(product.getIsCoupon() == 0){
                    order.setMerRate(mer.getSubRate());
                }else{
                    order.setMerRate(mer.getSubCouponRate());
                }
            }
            int ret = productOrderMapper.insert(order);
            if(ret <= 0){
                throw new TransactionalException("product order insert error");
            }else{
                long order_id = order.getId();

                ProductOrderRelation orderRelation = new ProductOrderRelation();
                orderRelation.setOrderId(order_id);
                orderRelation.setPayNo(payNo);
                orderRelation.setAllPrice(new BigDecimal(allPrice));
                ret = orderRelationMapper.insert(orderRelation);
                if(ret <= 0){
                    throw new TransactionalException("orderRelationMapper insert error");
                }

                for (int i = 0; i < count;i++){

                    ProductOrderInfo orderInfo = new ProductOrderInfo();
                    orderInfo.setCount(1);
                    orderInfo.setProductId(attrValue.getProductId());
                    orderInfo.setOrderId(order_id);
                    orderInfo.setSinglePrice(attrValue.getPrice());
                    orderInfo.setOriginPrice(attrValue.getOtPrice());
                    orderInfo.setTotalMoney(attrValue.getPrice());
                    orderInfo.setActivityMinsMoney(new BigDecimal(0));
                    orderInfo.setState(1);
                    orderInfo.setCreateTime(new Date());
                    orderInfo.setSkuId(attrValue.getId());
                    orderInfo.setVerifyCode(OrderUtil.getVerfiyNoAndRandom());//核销码
                    orderInfo.setVerifyCount(0);
                    orderInfo.setIsVerify(0);
                    orderInfo.setIsDel(0);
                    orderInfo.setOpSysUserId(0L);
                    orderInfo.setDelSysUserId(0L);
                    orderInfo.setSettlementState(0);
                    if(mer!=null){
                        orderInfo.setMerRate(mer.getSubRate());
                    }
                    if(userAddress != null){
                        orderInfo.setPropertyId(user.getPropertyId());
                        orderInfo.setEstateId(user.getEstateId());
                    }

                    ret = productOrderInfoMapper.insert(orderInfo);
                    if(ret <=0){
                        throw new TransactionalException("product order info insert error");
                    }
                }
                order.setPlatformSplit(new BigDecimal(d1Total));
                order.setProprietorSplit(new BigDecimal(d2Total));
                order.setPropertySplit(new BigDecimal(d3Total));

                //商家手续费和结算金额计算
                if(mer != null){
                    order.setMerSubType(mer.getSubType());
                    order.setMerFee(new BigDecimal(dTotalFee));
                    order.setMerSettlement(new BigDecimal(dTotalSettlement));
                }
                ret = productOrderMapper.updateById(order);
                if(ret <= 0){
                    throw new TransactionalException("productOrderMapper insert error");
                }
            }
            return order.getId();
        }catch (Exception ex){
            ex.printStackTrace();
            throw new TransactionalException("UserSignRecord insert error");
        }
    }

    @Transactional
    @Override
    public long buyCoupon(User user, int order_type, int count, MerCoupon merCoupon, String remark, String platform) throws TransactionalException {
        try{
            double allPrice = 0;
            double d1Total = 0, d2Total = 0, d3Total = 0, dTotalFee = 0, dTotalSettlement = 0;
            allPrice = count * merCoupon.getPrice().doubleValue();

            PlatformPay platformPay = platformPayService.getDefaultAccount();
            Parameter parameter = parameterService.getParameterById(1);
            String payNo = OrderUtil.getPayNo();
            //添加 订单表数据
            ProductOrder order = new ProductOrder();
            String orderNo = OrderUtil.getOrderNoByTimespan(platformPay.getSysCode());
            if(platform.equals("wxmini")){
                order.setPlatform(0);
            }else{
                order.setPlatform(1);
            }
            order.setPayNo(payNo);
            order.setOrderNo(orderNo);
            order.setOutTradeNo(orderNo);
            //订单类型  0 - 平台商品类  1 - 设备上的商品类  2 - 线下商家活动  3 - 商家优惠券 4 - 团购类
            order.setOrderType(order_type);
            order.setUserId(user.getId());
            order.setTotalPrice(new BigDecimal(allPrice));
            order.setCouponId(merCoupon.getId());
            order.setCouponPrice(merCoupon.getPrice());
            order.setCouponDikouPrice(merCoupon.getDikouPrice());
            order.setCouponName(merCoupon.getCouponName());
            order.setNickName(EmojiParser.parseToUnicode(user.getNickName()));

            order.setCreateTime(new Date());
            order.setTotalNum(count);
            order.setUserPhone(user.getPhoneNum());
            order.setPayPrice(new BigDecimal(allPrice));
            order.setFee(new BigDecimal(allPrice * 0.06 / 100));
            order.setStatus(0);//订单状态 0 - 未支付  1 - 支付中  2 - 已支付 3 - 待发货  4 - 待收货  5 - 待评价 6 - 已评价  7 - 订单取消  8 - 退货中 9 - 已退款
            order.setRemark(remark);
            order.setIsMerCheck(0);//是否核销
            order.setVerifyCode(OrderUtil.getVerfiyNo());//核销码
            order.setSettlementState(0);
            if(merCoupon!=null){
                order.setMerId(merCoupon.getMerId());
            }

            order.setPayType(parameter.getProductPayPlatform());

            order.setPayPlatformId(0);
            if(platformPay!=null) {
                if(parameter.getProductPayPlatform() == 1){
                    order.setPayPlatformId(platformPay.getId());
                }
            }

            order.setIsAppointment(0);
            order.setRealName(user.getNickName());
            order.setPropertyId(user.getPropertyId());
            order.setEstateId(user.getEstateId());
            order.setMerSubType(1);
            order.setMerRate(merCoupon.getSubRate());
            int ret = productOrderMapper.insert(order);
            if(ret <= 0){
                throw new TransactionalException("product order insert error");
            }else{
                long order_id = order.getId();

                ProductOrderRelation orderRelation = new ProductOrderRelation();
                orderRelation.setOrderId(order_id);
                orderRelation.setPayNo(payNo);
                orderRelation.setAllPrice(new BigDecimal(allPrice));
                ret = orderRelationMapper.insert(orderRelation);
                if(ret <= 0){
                    throw new TransactionalException("orderRelationMapper insert error");
                }

                // 当前优惠券的分成金额
//                double totalSplitMoney = MathUtil.getDoubleUp(merCoupon.getPrice().doubleValue() * count *  merCoupon.getSubRate().doubleValue() / 100);
                //计算当前商品的分润以及手续费
                //手续费
                double fee = MathUtil.getDoubleUp(merCoupon.getPrice().doubleValue() * count *  merCoupon.getSubRate().doubleValue() / 100);
                order.setMerFee(new BigDecimal(fee));//商家手续费（分佣）
                //结算金额
                double settlement = merCoupon.getPrice().doubleValue() - fee;
                order.setMerSettlement(new BigDecimal(settlement));

                QueryWrapper<PlatformSplit> qw = new QueryWrapper<>();
                qw.eq("split_type","proportion");//按照比例分成
                qw.last("limit 1");
                PlatformSplit platformSplit = platformSplitMapper.selectOne(qw);
                if(platformSplit != null){
                    //平台
                    double d1 = fee * platformSplit.getPlatformSplit().doubleValue() / 100;
                    d1Total += d1 * count;
                    //业主
                    double d2 = fee * platformSplit.getProprietorSplit().doubleValue() / 100;
                    d2Total += d2 * count;
                    //物业公司
                    double d3 = fee * platformSplit.getPropertySplit().doubleValue() / 100;
                    d3Total += d3 * count;
                }
                order.setPlatformSplit(new BigDecimal(d1Total));
                order.setProprietorSplit(new BigDecimal(d2Total));
                order.setPropertySplit(new BigDecimal(d3Total));
                order.setMerSettlement(new BigDecimal(dTotalSettlement));
                ret = productOrderMapper.updateById(order);
                if(ret <= 0){
                    throw new TransactionalException("productOrderMapper insert error");
                }
            }
            return order.getId();
        }catch (Exception ex){
            ex.printStackTrace();
            throw new TransactionalException("UserSignRecord insert error");
        }
    }

    @Override
    public long buyMerOffline(User user, int order_type, Mer mer, double price, String remark,String platform) throws TransactionException {
        try{
            double allPrice = price;
            double d1Total = 0, d2Total = 0, d3Total = 0, dTotalFee = 0, dTotalSettlement = 0;
            int count = 1;

            PlatformPay platformPay = platformPayService.getDefaultAccount();
            if(mer!= null){
                if(mer.getPayPlatformId() > 0){
                    platformPay = platformPayService.getById(mer.getPayPlatformId());
                }
            }

            Parameter parameter = parameterService.getParameterById(1);

            String payNo = OrderUtil.getPayNo();
            //添加 订单表数据
            ProductOrder order = new ProductOrder();
            String orderNo = OrderUtil.getOrderNoByTimespan(platformPay.getSysCode());

            order.setPlatform(0);
            order.setPayNo(payNo);
            order.setOrderNo(orderNo);
            order.setMerId(mer.getId());
            order.setOutTradeNo(orderNo);

            //订单类型  0 - 平台商品类  1 - 设备上的商品类  2 - 线下商家活动  3 - 商家优惠券 4 - 团购类
            order.setOrderType(order_type);
            order.setUserId(user.getId());
            order.setTotalPrice(new BigDecimal(allPrice));
            order.setPayPrice(new BigDecimal(allPrice));
            if(mer!= null){
                if(mer.getSubRate()!= null){
                    double fee = order.getPayPrice().doubleValue() * mer.getSubRate().doubleValue() / 100;
                    System.out.println("手续费" + MathUtil.getDoubleUp(fee));
                    order.setMerFee(new BigDecimal(MathUtil.getDoubleUp(fee)));
                    double settlePrice = order.getPayPrice().doubleValue() - fee;
                    System.out.println("结算金额 ： " + MathUtil.getDoubleUp(settlePrice));
                    order.setMerSettlement(new BigDecimal(MathUtil.getDoubleUp(settlePrice)));
                }
            }else{
                double rate = 0.6;
                double fee = order.getPayPrice().doubleValue() * rate / 100;
                order.setFee(new BigDecimal(allPrice * rate / 100));
                order.setMerFee(new BigDecimal(allPrice * rate / 100));
                double settlePrice = order.getPayPrice().doubleValue() - fee;
                order.setMerSettlement(new BigDecimal(MathUtil.getDoubleUp(settlePrice)));
            }

            order.setCouponId(0);
            order.setCouponPrice(new BigDecimal(0));
            order.setCouponDikouPrice(new BigDecimal(0));
            order.setNickName(EmojiParser.parseToUnicode(user.getNickName()));

            order.setUserCouponId(0);
            order.setUserCouponPrice(new BigDecimal(0));
            order.setUserCouponDikouPrice(new BigDecimal(0));

            order.setPayType(parameter.getProductPayPlatform());
//            order.setPayType(0);

            order.setPayPlatformId(0);
            if(platformPay != null) {
                if(parameter.getProductPayPlatform() == 1){
                    //如果商家配置了支付商户
                    if(mer.getPayPlatformId() > 0){
                        platformPay = platformPayService.getById(mer.getPayPlatformId());
                    }
                    order.setPayPlatformId(platformPay.getId());
                }
            }

            order.setCreateTime(new Date());
            order.setTotalNum(1);
            order.setStatus(0);//订单状态 0 - 未支付  1 - 支付中  2 - 已支付 3 - 待发货  4 - 待收货  5 - 待评价 6 - 已评价  7 - 订单取消  8 - 退货中 9 - 已退款
            order.setRemark(remark);
            order.setIsMerCheck(0);//是否核销
            order.setVerifyCode(OrderUtil.getVerfiyNo());//核销码
            order.setSettlementState(0);
            order.setIsAppointment(0);
            order.setUserPhone(user.getPhoneNum());
            order.setRealName(user.getNickName());
            order.setPropertyId(user.getPropertyId());
            order.setEstateId(user.getEstateId());
            order.setMerSubType(1);
            order.setMerRate(mer.getSubRate());
            int ret = productOrderMapper.insert(order);
            if(ret <= 0){
                throw new TransactionalException("product order insert error");
            }else{
//                long order_id = order.getId();
//
//                ProductOrderRelation orderRelation = new ProductOrderRelation();
//                orderRelation.setOrderId(order_id);
//                orderRelation.setPayNo(payNo);
//                orderRelation.setAllPrice(new BigDecimal(allPrice));
//                ret = orderRelationMapper.insert(orderRelation);
//                if(ret <= 0){
//                    throw new TransactionalException("orderRelationMapper insert error");
//                }
//
//                // 当前优惠券的分成金额
////                double totalSplitMoney = MathUtil.getDoubleUp(merCoupon.getPrice().doubleValue() * count *  merCoupon.getSubRate().doubleValue() / 100);
//                //计算当前商品的分润以及手续费
//                //手续费
//                double fee = MathUtil.getDoubleUp(allPrice *  mer.getSubRate().doubleValue() / 100);
//                order.setMerFee(new BigDecimal(fee));//商家手续费（分佣）
//                //结算金额
//                double settlement = allPrice - fee;
//                order.setMerSettlement(new BigDecimal(settlement));
//
//                QueryWrapper<PlatformSplit> qw = new QueryWrapper<>();
//                qw.eq("split_type","proportion");//按照比例分成
//                qw.last("limit 1");
//                PlatformSplit platformSplit = platformSplitMapper.selectOne(qw);
//                if(platformSplit != null){
//                    //平台
//                    double d1 = fee * platformSplit.getPlatformSplit().doubleValue() / 100;
//                    d1Total += d1 * count;
//                    //业主
//                    double d2 = fee * platformSplit.getProprietorSplit().doubleValue() / 100;
//                    d2Total += d2 * count;
//                    //物业公司
//                    double d3 = fee * platformSplit.getPropertySplit().doubleValue() / 100;
//                    d3Total += d3 * count;
//                }
//                order.setPlatformSplit(new BigDecimal(d1Total));
//                order.setProprietorSplit(new BigDecimal(d2Total));
//                order.setPropertySplit(new BigDecimal(d3Total));
//                order.setMerSettlement(new BigDecimal(dTotalSettlement));
//                ret = productOrderMapper.updateById(order);
//                if(ret <= 0){
//                    throw new TransactionalException("productOrderMapper insert error");
//                }
            }
            return order.getId();
        }catch (Exception ex){
            ex.printStackTrace();
            throw new TransactionalException("UserSignRecord insert error");
        }
    }

    /**
     *  订单核销成功后  要计算分成
     * @param order
     * @return
     */
    @Override
    @Transactional
    public int verifyOrder(ProductOrder order, ProductOrderInfo orderInfo) {
        int ret = 0;
        try{
            orderInfo.setIsVerify(1);
            orderInfo.setVerifyCount(1);
            ret = productOrderInfoMapper.updateById(orderInfo);
            if(ret <= 0){
                throw new TransactionalException("updateOrderState insert error");
            }

            boolean bl = true;

            QueryWrapper<ProductOrderInfo> qwInfos = new QueryWrapper<>();
            qwInfos.eq("order_id", orderInfo.getOrderId());
            qwInfos.eq("state",1);
            qwInfos.eq("is_del", 0);
            List<ProductOrderInfo> infos = productOrderInfoMapper.selectList(qwInfos);
            for(ProductOrderInfo orderInfo1 : infos){
                if(orderInfo1.getCount() > orderInfo1.getVerifyCount()){
                    bl = false;
                    break;
                }
            }
            if(bl){
                //更改订单状态
                //订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销  4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
                order.setVerifyTime(new Date());
                //是否核销  0 - 未核销 1 - 发起核销申请 2 - 已核销
                order.setIsMerCheck(2);
                ret = updateOrderState(order,3);
                if(ret <= 0){
                    throw new TransactionalException("updateOrderState insert error");
                }
                if(order.getOrderType() == 3){
                    UserMerCoupon userMerCoupon = userMerCouponMapper.selectById(order.getCouponId());
                    if(userMerCoupon!=null){
                        userMerCoupon.setState(1);
                        ret = userMerCouponMapper.updateById(userMerCoupon);
                        if(ret <= 0){
                            throw new TransactionalException("userMerCouponMapper insert error");
                        }
                    }
                }
            }else{
                //是否核销  0 - 未核销 1 - 发起核销申请 2 - 已核销
                order.setIsMerCheck(0);
                ret = updateOrderState(order,2);
                if(ret <= 0){
                    throw new TransactionalException("updateOrderState insert error");
                }
            }

            // 非 包含 暖心保的订单 处理   暖心保 不分成
            Product product = productMapper.selectById(orderInfo.getProductId());
            if(product!=null){
                User merUser = merUserService.getMerAdminByUser(order.getMerId());
                SplitAccount splitAccount = splitAccountService.getAdminAccountByType(order.getMerId(),3);
                if(splitAccount == null){
                    splitAccount = new SplitAccount();
                    splitAccount.setAccountId(order.getMerId());
                    splitAccount.setAccountType(3);
                    splitAccount.setSplitMoney(new BigDecimal(0));
                    splitAccount.setChargerMoney(new BigDecimal(0));
                    splitAccount.setFreezen(new BigDecimal(0));
                    splitAccount.setUserId(merUser.getId());
                    ret = splitAccountMapper.insert(splitAccount);
                    if(ret <= 0){
                        throw new TransactionalException("splitAccountMapper update error");
                    }
                }
            }

            ret = productOrderInfoMapper.updateById(orderInfo);
            if(ret <= 0){
                throw new TransactionalException("updateOrderState insert error");
            }
            ret = productOrderMapper.updateById(order);
            if(ret <= 0){
                throw new TransactionalException("productOrderMapper updateById error");
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new TransactionalException("splitMoney update error");
        }
        return ret;
    }

    @Override
    public ProductOrder getOrderByOrderNo(String order_no) {
        return productOrderMapper.getOrderByOrderNo(order_no);
    }

    /**
     * 更新订单的状态
     * @return
     */
    @Override
    public int updateOrderState(ProductOrder order, int state) {
        order.setStatus(state);
        return productOrderMapper.updateById(order);
    }

    @Override
    public int getOrderCountByState(Integer user_id, Integer state) {
        return productOrderMapper.getOrderCountByState(user_id,state);
    }

    @Override
    public int getOrderCountByTime(Integer seller_id, Integer state, Date begin_date,Date end_date) {
        return productOrderMapper.getOrderCountByTime(seller_id,state,begin_date,end_date);
    }

    /**
     * 买家查订单
     * @param userId
     * @param state
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Override
    public List<ProductOrder> queryListByUserId(int userId,int order_type, int state, int pageIndex, int pageSize) {
        QueryWrapper<ProductOrder> qw1 = new QueryWrapper<>();
        qw1.eq("user_id",userId);
//        qw1.eq("order_type",order_type);
        qw1.eq("is_del",0);
        if(state != -1){
            if(state == 0){
                Integer[] states = {0,1};
                qw1.in("status", Arrays.asList(states));
            }else{
                qw1.eq("status",state);
            }
        }
        // 待评价订单  只是 针对于 普通商品的订单
        if(state == 3){
            qw1.eq("order_type", 0);
        }
        qw1.orderByDesc("create_time");
        List<ProductOrder> list = productOrderMapper.getPageEntityList(qw1,pageIndex,pageSize);
        if(list != null && list.size() > 0){
            for(ProductOrder order : list){
                if(order.getOrderType() == 0 || order.getOrderType() == 4 || order.getOrderType() == 6){
                    Mer mer = merMapper.selectById(order.getMerId());
                    if(mer!=null){
                        order.setImgUrl(imgPrefix + mer.getShopLogo());
                    }
                    order.setRealName(EmojiParser.parseToUnicode(order.getRealName()));
                    order.setMer(mer);

                    QueryWrapper<ProductOrderInfo> qwInfos = new QueryWrapper<>();
                    qwInfos.eq("order_id", order.getId());
                    qwInfos.eq("state",1);
                    qwInfos.eq("is_del", 0);
                    List<ProductOrderInfo> infos = productOrderInfoMapper.selectList(qwInfos);
                    if(CollUtil.isNotEmpty(infos)){
                        for (ProductOrderInfo info : infos){
                            Product product = productService.getProductInfoById(info.getProductId(), 0);
                            if(product!=null){
                                info.setProductName(product.getStoreName());
                                info.setImgUrl(product.getImage());
                            }

                            if(StrUtil.isEmpty(info.getSkuName())) {
                                ProductAttrValue attrValue = productAttrValueMapper.selectById(info.getSkuId());
                                if (attrValue != null) {
                                    info.setSkuName(attrValue.getSku());
                                }
                            }
                        }
                    }
                    order.setInfos(infos);
                }else if(order.getOrderType() == 2 || order.getOrderType() == 3){
                    Mer mer = merMapper.selectById(order.getMerId());
                    if(mer!=null){
                        order.setImgUrl(imgPrefix + mer.getShopLogo());
                    }
                    order.setMer(mer);
                }
            }
        }
        return list;
    }

    /**
     * 商家查订单
     * @param merId
     * @param state
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Override
    public List<ProductOrder> queryListByMerId(int merId, int state, int pageIndex, int pageSize) {
        QueryWrapper<ProductOrder> qw1 = new QueryWrapper<>();
        ////订单状态订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）
        // 3 - 已核销  4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
        qw1.eq("mer_id",merId);
        qw1.eq("is_del",0);
        if(state != -1){
            if(state != 6){
                qw1.eq("status",state);
            }else{
                Integer[] states = new Integer[]{ 6, 7, 8, 9 };
                qw1.in("status",states);
            }
        }
        if(state == 1){
            qw1.ne("is_mer_check",2);
        }
        qw1.orderByDesc("create_time");
        List<ProductOrder> list = productOrderMapper.getPageEntityList(qw1,pageIndex,pageSize);
        if(CollUtil.isNotEmpty(list)) {
            for(ProductOrder order : list) {
                order.setRealName(EmojiParser.parseToUnicode(order.getRealName()));
                QueryWrapper<ProductOrderInfo> qwInfo = new QueryWrapper<>();
                qwInfo.eq("order_id",order.getId());
                qwInfo.eq("is_del", 0);
                qwInfo.orderByAsc("is_tableware");
                List<ProductOrderInfo> infos = productOrderInfoMapper.selectList(qwInfo);
                if(CollUtil.isNotEmpty(infos)){
                    for (ProductOrderInfo info : infos){
                        Product product = productService.getProductInfoById(info.getProductId(), 0);
                        if(product != null){
                            info.setProductName(product.getStoreName());
                            info.setImgUrl(product.getImage());
                        }

                        if(StrUtil.isEmpty(info.getSkuName())) {
                            ProductAttrValue attrValue = productAttrValueMapper.selectById(info.getSkuId());
                            if (attrValue != null) {
                                info.setSkuName(attrValue.getSku());
                            }
                        }
                    }
                }
                order.setInfos(infos);
            }
        }
        return list;
    }

    /**
     *  支付成功后的 订单信息处理
     * @param order
     * @return
     * @throws TransactionalException
     */
    @Override
    @Transactional
    public int buyNormalUpdate(ProductOrder order, User user) throws TransactionalException{
        int ret = 0;
        try{
            //订单类型  0 - 平台商品类  1 - 设备上的商品类  2 - 线下商家活动  3 - 购买商家抵扣券 4 - 团购类
            if(order.getOrderType() == 3){//购买商家抵扣券
                MerCoupon merCoupon = merCouponMapper.selectById(order.getCouponId());
                if(merCoupon!=null){
                    UserMerCoupon userMerCoupon = new UserMerCoupon();
                    userMerCoupon.setCouponType(merCoupon.getCouponType());
                    userMerCoupon.setUserId(order.getUserId());
                    userMerCoupon.setCreateTime(new Date());
                    userMerCoupon.setCouponId(order.getCouponId());
                    userMerCoupon.setCouponName(merCoupon.getCouponName());
                    userMerCoupon.setPrice(merCoupon.getPrice());
                    userMerCoupon.setDikouPrice(merCoupon.getDikouPrice());
                    userMerCoupon.setState(0);
                    userMerCoupon.setMerName(merCoupon.getMerName());
                    if(merCoupon.getCouponType() == 1){
                        userMerCoupon.setBeginTime(merCoupon.getBeginTime());
                        userMerCoupon.setEndTime(merCoupon.getEndTime());
                    }
                    ret = userMerCouponMapper.insert(userMerCoupon);
                    if(ret <=0){
                        throw new TransactionalException("userMerCouponMapper updateById error");
                    }
                    int sales = merCoupon.getSales();
                    merCoupon.setSales(sales + 1);
                    ret = merCouponMapper.updateById(merCoupon);
                    if(ret <=0){
                        throw new TransactionalException("merCouponMapper updateById error");
                    }
                }
            }else{
                //减库存
                QueryWrapper<ProductOrderInfo> qwInfo = new QueryWrapper<>();
                qwInfo.eq("order_id",order.getId());
                qwInfo.eq("is_del", 0);
                List<ProductOrderInfo> orderInfos = productOrderInfoMapper.selectList(qwInfo);
                for (ProductOrderInfo orderInfo : orderInfos){
                    ProductAttrValue attrValue = productAttrValueMapper.selectById(orderInfo.getSkuId());
                    if(attrValue != null){
                        int count = orderInfo.getCount();
                        int attrCount = attrValue.getStock();
                        attrValue.setStock(attrCount - count);
                        int saleCount = attrValue.getSales();
                        attrValue.setSales(saleCount + orderInfo.getCount());
                        ret =  productAttrValueMapper.updateById(attrValue);
                        if(ret <=0){
                            throw new TransactionalException("productAttrValueMapper updateById error");
                        }
                        int countProduct = 0;
                        Product product = productMapper.selectById(orderInfo.getProductId());
                        if(product != null){
                            countProduct = product.getSales();
                            product.setSales(countProduct + orderInfo.getCount());
                            ret = productMapper.updateById(product);
                            if(ret <=0){
                                throw new TransactionalException("productMapper updateById error");
                            }
                        }
                    }
                }
            }

            //更改订单支付状态
            ret = productOrderMapper.updateById(order);
            if(ret <=0){
                throw new TransactionalException("productOrderMapper updateById error");
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new TransactionalException("userIntegralRecordMapper insert error");
        }
        return ret;
    }

    @Override
    public int buyNormalOffline(ProductOrder order) {
        int ret = 0;
        try{
            Mer mer = merMapper.selectById(order.getMerId());
            if(mer != null) {
                if(mer.getSubRate() != null){
                    double fee = order.getPayPrice().doubleValue() * mer.getSubRate().doubleValue() / 100;

                    System.out.println("手续费" + MathUtil.getDoubleUp(fee));
                    order.setMerFee(new BigDecimal(MathUtil.getDoubleUp(fee)));
                    double settlePrice = order.getPayPrice().doubleValue() - fee;
                    System.out.println("结算金额 ： " + MathUtil.getDoubleUp(settlePrice));

                    order.setMerSettlement(new BigDecimal(MathUtil.getDoubleUp(settlePrice)));
                }
            }

            ret = productOrderMapper.updateById(order);
            if(ret <=0){
                throw new TransactionalException("productOrderMapper updateById error");
            }


            //计算分成
//            ret = splitMoney(order);
//            if(ret <= 0){
//                throw new TransactionalException("splitMoney update error");
//            }
        }catch (Exception e){
            e.printStackTrace();
            throw new TransactionalException("userIntegralRecordMapper insert error");
        }
        return ret;
    }

    @Override
    public WalletDto getAllMoneyByMerIdAndTime(Map<String, Object> map) {
        return productOrderMapper.getAllMoneyByMerIdAndTime(map);
    }

    @Override
    public ProductOrder getOrderDetail(long orderId) {
        ProductOrder order = productOrderMapper.selectById(orderId);
        if(order != null){
            Mer mer = merMapper.selectById(order.getMerId());
            if(mer != null){
                order.setImgUrl( imgPrefix + mer.getShopLogo());
                order.setMer(mer);
            }

            if(order.getOrderType() == 0 || order.getOrderType() == 4 || order.getOrderType() == 6){
                List<ProductOrderInfo> infos = productOrderInfoService.selectListByOrderId(mer,order.getId());
                if(infos != null && infos.size() > 0){
                    for(ProductOrderInfo orderInfo : infos){
                        if(StrUtil.isNotEmpty(orderInfo.getQrCode())){
                            orderInfo.setQrCode(imgPrefix + orderInfo.getQrCode());
                        }
                        Product product = productService.getProductInfoById(orderInfo.getProductId(), 0);
                        if(product != null){
                            orderInfo.setProductName(product.getStoreName());
                            orderInfo.setImgUrl(product.getImage());
                        }

                        ProductAttrValue sku = productAttrValueMapper.selectById(orderInfo.getSkuId());
                        if(sku != null){
                            orderInfo.setAttrValue(sku);

                            if(StrUtil.isEmpty(orderInfo.getSkuName())) {
                                orderInfo.setSkuName(sku.getSku());
                            }
                        }
                    }
                }
                order.setInfos(infos);

                //过期时间
                order.setGroupExpireTime(0L);

                List<UserMerCoupon> coupons = userMerCouponService.getMyAllEnableCoupon(order.getUserId(),order.getMerId());
                order.setCoupons(coupons);
                order.setCouponCount(coupons.size());

                QueryWrapper<UserCoupons> qwCoupon = new QueryWrapper<>();
                qwCoupon.eq("user_id",order.getUserId());
                qwCoupon.eq("state",0);
                List<UserCoupons> userCoupons = userCouponsMapper.selectList(qwCoupon);
                order.setUserCoupons(userCoupons);

            }else if(order.getOrderType() == 3){
                MerCoupon merCoupon = merCouponMapper.selectById(order.getCouponId());
                if(merCoupon!=null){
                    order.setProductName(merCoupon.getCouponName());
                }
            }

            if(!StrUtil.isNotEmpty(order.getRealName())){
                order.setRealName(EmojiParser.parseToUnicode(order.getRealName()));
            }
            order.setTotalPayMoney(new BigDecimal(MathUtil.getDoubleUp(order.getPayPrice().doubleValue())));
            order.setOutTradeNo("");
        }
        return order;
    }

    @Override
    public int getLimitOrderByProductId(int userId, int productId) {
        return productOrderMapper.getLimitOrderByProductId(userId, productId);
    }

    @Override
    @Transactional
    public int resetOrderFee() {
        int ret = 0;
        try {
            QueryWrapper<ProductOrder> qw = new QueryWrapper<>();
//            qw.eq("mer_id", 26);
//            qw.eq("status", 3);//已核销订单
            qw.isNull("mer_fee");//已核销订单
//            qw.last("limit 10");//已核销订单
            List<ProductOrder> list = productOrderMapper.selectList(qw);
            if(CollUtil.isNotEmpty(list)){
                for (ProductOrder order : list){
                    Mer mer = merMapper.selectById(order.getMerId());
                    if(mer != null){
                        order.setMerRate(mer.getSubRate());
                        if(mer.getSubRate()!= null){
                            double fee = order.getPayPrice().doubleValue() * mer.getSubRate().doubleValue() / 100;

                            System.out.println("手续费" + MathUtil.getDoubleUp(fee));
                            order.setMerFee(new BigDecimal(MathUtil.getDoubleUp(fee)));
                            double settlePrice = order.getPayPrice().doubleValue() - fee;
                            System.out.println("结算金额 ： " + MathUtil.getDoubleUp(settlePrice));

                            order.setMerSettlement(new BigDecimal(MathUtil.getDoubleUp(settlePrice)));
                        }
                        productOrderMapper.updateById(order);
                    }else{

                        double fee = order.getPayPrice().doubleValue() * 0.6 / 100;

                        System.out.println("手续费" + MathUtil.getDoubleUp(fee));
                        order.setMerFee(new BigDecimal(MathUtil.getDoubleUp(fee)));
                        double settlePrice = order.getPayPrice().doubleValue() - fee;
                        System.out.println("结算金额 ： " + MathUtil.getDoubleUp(settlePrice));

                        order.setMerSettlement(new BigDecimal(MathUtil.getDoubleUp(settlePrice)));
                        productOrderMapper.updateById(order);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ret;
    }
}
